package com.yupi.longoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.yupi.longoj.model.dto.question.JudgeCase;
import com.yupi.longoj.model.dto.question.JudgeConfig;
import com.yupi.longoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.longoj.model.entity.Question;
import com.yupi.longoj.model.enums.JudgeInfoMessageEnum;

import java.util.List;
import java.util.Optional;

/**
 * java程序的判题策略
 */
public class JavaLanguageJudgeStrategy implements JudgeStrategy{

    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Long memory = Optional.ofNullable(judgeInfo.getMemory()).orElse(0L);
        Long time = Optional.ofNullable(judgeInfo.getTime()).orElse(0L);
        Question question = judgeContext.getQuestion();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCEPTED;
        JudgeInfo judgeInfoReponse = new JudgeInfo();
        judgeInfoReponse.setMemory(memory);
        judgeInfoReponse.setTime(time);

        //1.先判断沙箱执行的结果输出数量是和预期输出数量相等
        if(inputList.size() != outputList.size()){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoReponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoReponse;
        }
        //2.判断每一项输出和预期输出是否相等
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase=judgeCaseList.get(i);
            if (!outputList.get(i).equals(judgeCase.getOutput())){
                judgeInfoMessageEnum=JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoReponse.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoReponse;
            }
        }
        //3.判断题目的限制是否符合要求
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long needTimeLimit = judgeConfig.getTimeLimit();
        Long needMemoryLimit = judgeConfig.getMemoryLimit();

        //内存限制
        if (memory > needMemoryLimit){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoReponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoReponse;
        }
        //时间限制
        //java程序本身需要额外执行10秒钟
        Long JAVA_PROGRAM_TIME=10000L;
        if ((time - JAVA_PROGRAM_TIME) > needTimeLimit){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoReponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoReponse;
        }
        judgeInfoReponse.setMessage(judgeInfoMessageEnum.getValue());
        return judgeInfoReponse;
    }
}
